package cn.itcast.multi.thread.lock;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.StampedLock;

/**
 * ClassName: ShareData  
 * (读写锁共享数据--临界区)
 * 读模板与写模板
 * @author zhangtian  
 * @version
 */
public class StampLockShareData {
	// 要操作的共享数据
	 private static int data = 100;
	 // 读锁
	 private final StampedLock stampedLock = new StampedLock() ;

	 /**
	  * 读取数据
	  */
	public void read() {
		// 乐观读
		long stampRead = stampedLock.tryOptimisticRead() ;
	 	// 校验stamp
		if (!stampedLock.validate(stampRead)) {
		// 升级为悲观读锁
		stampRead = stampedLock.readLock() ;
		try {
			System.out.println("正在准备读取数据.......");
			Thread.sleep(new Random().nextInt(10)*1000);
			System.out.println("读到的数据" + data);
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			// 释放悲观读锁
		 	stampedLock.unlock(stampRead);
		}
	 }
	}
	
	 /**
	  * 写数据
	  */
	public void write() {
		long stampWrite = stampedLock.writeLock() ;
		try {
			Thread.sleep(new Random().nextInt(10)*1000);
			System.out.println("正在准备写数据........");
			data--;
			System.out.println("写入数据" + data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			stampedLock.unlock(stampWrite);
		}
	}
}
